using MyBlogServer.Components;
using MyBlogServer.Data;
using MyBlogServer.Services;
using MyBlogServer.Controllers;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Components.Authorization;
using MyBlogServer;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

builder.Services.AddControllers(); // 添加控制器支持

// Add application services
builder.Services.AddApplicationServices();

// 添加 IHttpContextAccessor 服务
builder.Services.AddHttpContextAccessor();

// 添加JWT认证服务（主要用于API控制器）
var jwtSettings = builder.Configuration.GetSection("Jwt");
var key = Encoding.ASCII.GetBytes(jwtSettings["SecretKey"]);

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.RequireHttpsMetadata = false;
    options.SaveToken = true;
    options.IncludeErrorDetails = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ValidateIssuer = true,
        ValidIssuer = jwtSettings["Issuer"],
        ValidateAudience = true,
        ValidAudience = jwtSettings["Audience"],
        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero
    };
});

builder.Services.AddAuthorization(options =>
{
    // 移除全局认证要求，改为在需要的地方使用[Authorize]特性
    // 只对特定路径要求认证
    options.FallbackPolicy = null;
});

// Add BlogContext service
builder.Services.AddSingleton<BlogContext>(provider =>
{
    var configuration = provider.GetRequiredService<IConfiguration>();
    var connectionString = configuration.GetConnectionString("DefaultConnection") 
        ?? "Data Source=blog.db";
    return new BlogContext(connectionString);
});

// Add services
builder.Services.AddScoped<PostService>();
builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<CustomAuthenticationStateProvider>();
builder.Services.AddScoped<AuthenticationStateProvider>(provider => provider.GetRequiredService<CustomAuthenticationStateProvider>());

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

// 添加静态文件中间件以提供wwwroot中的文件
app.UseStaticFiles();

// 使用认证中间件
app.UseAuthentication();
app.UseAuthorization();

// 添加控制器端点
app.MapControllers();

// Initialize database
Console.WriteLine("开始初始化数据库");
var blogContext = app.Services.GetRequiredService<BlogContext>();
blogContext.InitializeDatabase();
Console.WriteLine("数据库初始化完成");

app.UseAntiforgery();

app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

app.Run();